package com.lab.network.model;

import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lab.logtrack.AppLog;
import com.lab.network.config.CtResponseCode;

import java.util.List;

public class CtApiResponse {

    public int code;
    public String msg;
    public Object result;

    private ParseType parseType;

    private String apiName;

    private String asResponseString;

    public CtApiResponse() {
    }

    public CtApiResponse(ParseType parseType) {
        this.parseType = parseType;
    }

    public String getApiName() {
        return apiName;
    }

    public void setApiName(String apiName) {
        this.apiName = apiName;
    }

    public String parseResponse(String response) {
        this.asResponseString = response;
        JSONObject json = JSONObject.parseObject(response);
        Integer code = json.getInteger("code");
        this.code = code != null ? code : -1;
        this.msg = json.getString("msg");
        this.result = json.get("result");
        return json.toString();
    }


    public CtApiResponse reSerializeData(ParseType parseType) {
        if (result instanceof JSON && parseType != null) {
            if (ResultType.ARRAY.equals(parseType.resultType)) {
                AppLog.d("parse array"+((JSON) result).toJSONString());
                List<? extends Object> objectList = JSON.parseArray(this.result.toString(), (Class) parseType.type);
                this.result = objectList;
            } else {
                AppLog.d("parse object");
                if (parseType.type != null){
                    this.result = JSON.parseObject(this.result.toString(), parseType.type);
                }
            }
        }
        return this;
    }

    public boolean isResponseNormal(){
        return CtResponseCode.RESULT_OK == code;
    }

    public boolean isTokenInvalid(){
        return CtResponseCode.TOKEN_INVALID == code;
    }

    public boolean isResponseNotAvailable() {
        return CtResponseCode.NETWORK_CONNECT_NONE == code || CtResponseCode.DATA_ERROR == code;
    }

    @Override
    public String toString() {
        if (TextUtils.isEmpty(asResponseString)) {
            return "CtApiResponse{" +
                    "code=" + code +
                    ", msg='" + msg + '\'' +
                    ", result=" + result +
                    ", parseType=" + parseType +
                    ", apiName='" + apiName + '\'' +
                    '}';
        } else {
            return asResponseString;
        }

    }

    public int getCode() {
        return code;
    }

    public String getAsResponseString() {
        return asResponseString;
    }

    public void setAsResponseString(String asResponseString) {
        this.asResponseString = asResponseString;
    }
}
